using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WPFTemplateLib.WpfConverters.Core;

namespace WPFTemplateLib.WpfConverters
{
	/// <summary>
	/// [转换器] 将值转换为非负数。
	/// </summary>
	public class ValueToAbsConverter : ValueConverterBase
	{
		public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
		{
			if(value == null)
				return 0;

			try
			{
				// 尝试将值转换为 double
				double d = System.Convert.ToDouble(value, culture);
				d = Math.Abs(d);

				// 根据目标类型返回对应类型的非负数
				if(targetType == typeof(int))
					return (int)d;
				if(targetType == typeof(float))
					return (float)d;
				if(targetType == typeof(decimal))
					return (decimal)d;
				if(targetType == typeof(long))
					return (long)d;
				if(targetType == typeof(short))
					return (short)d;
				if(targetType == typeof(byte))
					return (byte)d;
				if(targetType == typeof(double))
					return d;
				if(targetType == typeof(string))
					return d.ToString(culture);

				// 默认返回 double
				return d;
			}
			catch
			{
				// 转换失败返回 0
				return 0;
			}
		}
	}
}
